using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;
using PersonnelConstants = PHSRAG.Insight21.Personnel.Constants;

namespace PHSRAG.Insight21
{
    /// <summary>
    /// The PayrollReport class supports the PayrollReport.aspx page.
    /// It displays the list of payroll run dates from which the user can select a date and download
    /// the Payroll report for the selected date. 
    /// By default the payroll report is downloaded in Excel Format.
    /// </summary>
    public partial class PayrollReport : BasePage
    {
        # region Instance Variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;

        # endregion

        #region Constants

        private const string ReportDateColumnName = "ReportDate";
        private const string ReportDateKey = "ReportDateKey_81C78FC2-5F65-4304-B1AF-6BD3B259973A";

        #endregion

        #region Private Properties

        /// <summary>
        /// Gets/Sets the payroll report date. 
        /// Returns an empty string if the date is not available in the page cache.
        /// Sets the selected date in the page cache.
        /// </summary>
        private string PayrollDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.PayrollReportPageKey) as Hashtable;
                return (h == null || h[ReportDateKey] == null) ? string.Empty : (string) h[ReportDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.PayrollReportPageKey) as Hashtable ?? new Hashtable();
                h[ReportDateKey] = value;
                pageCachePolicy.Cache(Keys.PayrollReportPageKey, h);
            }
        }

        #endregion

        # region Private Methods

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Initialize the bread crumb control,and load the reportDates dropdownlist with the list of report run dates.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ResultsCache.PurgeObject(cachePolicy);

                payrollBreadCrumb.Add("Payroll Report", Settings.GetKeyValue("SubNavigation.Personnel.PayrollReportURL", ""),
                    PersonnelConstants.DefaultSummaryPageRank);

                reportDownload.SQLReportName = SSRSRequest.ReportNames.Personnel.PayrollReport;

                LoadPayrollReportDates();
                reportDownload.EnableExcelLink = false;
                reportDownload.Visible = false;

                downloadPayrollReport.Attributes.Add("onclick", "javascript:return OnDownloadPayrollReport('" + SSRSRequest.ReportNames.Personnel.PayrollReport + "', '" +
                    HttpContext.Current.Server.UrlEncode(Page.Request.Url.ToString()) + "');");
            }
        }

        /// <summary>
        /// This method loads the reportDates dropdownlist with the list of Payroll report dates.
        /// If there is no data to bind, warn the user via the annunciator.
        /// </summary>
        private void LoadPayrollReportDates()
        {
            try
            {
                DataTable payrollReportDates = Personnel.PayrollReport.GetPayrollReportDates();
                if (payrollReportDates.Rows.Count > 0)
                {
                    reportDates.DataSource = payrollReportDates;
                    reportDates.DataTextField = ReportDateColumnName;
                    reportDates.DataBind();
                }
                else
                {
                    annunciator.Message = "No Payroll report dates defined.";
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// This method sets the selected payroll report date in the page cache policy.
        /// Case1: If the payroll report is run for the first time, the selected report date is put into the page cache.
        /// Case2: If the selected report date doesnt match with the cached date, then uncache the existing 
        /// PayrollReport instance from the business object and set the  selected report date in the page cache.
        /// </summary>
        private void SetPayrollDates()
        {
            string payrollDate = PayrollDate;
            if (payrollDate.Equals(string.Empty))
            {
                PayrollDate = Convert.ToDateTime(reportDates.SelectedItem.Text).ToShortDateString();
            }
            else if (!payrollDate.Equals(Convert.ToDateTime(reportDates.SelectedItem.Text).ToShortDateString()))
            {
                PayrollDate = Convert.ToDateTime(reportDates.SelectedItem.Text).ToShortDateString();
            }
        }

        #endregion

        #region Downloads

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = Utility.ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        #endregion

        #region Header Events

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            personnelSubNavigation.Reset();
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
            InitializeComponent();
            base.OnInit(e);

            this.reportDownload.FailedAction += new CommandEventHandler(OnDownloadFailed);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.insightHeader.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnHeaderNavigate);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}